package com.example.asyncquery.controller;

import com.example.asyncquery.model.QueryResult;
import com.example.asyncquery.service.QueryService;
import com.example.asyncquery.service.SseEmitterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
@RequestMapping("/api/sse")
@RequiredArgsConstructor
@Slf4j
public class SseController {

    private final SseEmitterService sseEmitterService;
    private final QueryService queryService;

    /**
     * 创建SSE连接
     * @param queryId 查询ID
     * @return SSE发射器
     */
    @GetMapping(value = "/subscribe/{queryId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter subscribe(@PathVariable String queryId) {
        log.info("客户端订阅查询更新: {}", queryId);
        
        // 创建新的SSE发射器
        SseEmitter emitter = sseEmitterService.createEmitter(queryId);
        
        // 立即发送当前查询状态
        QueryResult<?> currentResult = queryService.getQueryResult(queryId);
        if (currentResult != null) {
            sseEmitterService.sendQueryResultUpdate(queryId, currentResult);
        }
        
        return emitter;
    }
} 